package com.hethongviet.preventing.page;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.hethongviet.preventingmachine.R;

import com.hethongviet.preventingmachine.AppMain;
import com.hethongviet.preventingmachine.Config;
import com.hethongviet.preventingmachine.Constants;
import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.helps.dialog.DialogAlarm;
import com.hethongviet.preventingmachine.helps.dialog.DialogMessageBack;
import com.hethongviet.preventingmachine.helps.OnSMSMessageFailListener;
import com.hethongviet.preventingmachine.helps.OnSMSMessageListener;
import com.hethongviet.preventingmachine.helps.SMSHelper;
import com.hethongviet.preventingmachine.helps.SmsReceiverDefault;
import com.hethongviet.preventingmachine.helps.SoundPlay;
import com.hethongviet.preventingmachine.models.Tab;
import com.hethongviet.preventingmachine.helps.TabMenu;
import com.hethongviet.preventingmachine.helps.db.AccountSQLite;
import com.hethongviet.preventingmachine.helps.db.DeviceSQLite;
import com.hethongviet.preventingmachine.helps.db.RelaySQLite;
import com.hethongviet.preventingmachine.helps.db.ClientSQLite;
import com.hethongviet.preventingmachine.helps.db.SensorSQLite;
import com.hethongviet.preventingmachine.models.Account;
import com.hethongviet.preventingmachine.models.Device;
import com.hethongviet.preventingmachine.models.Relay;
import com.hethongviet.preventingmachine.models.SMS;
import com.hethongviet.preventingmachine.models.Client;
import com.hethongviet.preventingmachine.models.Sensor;
import com.hethongviet.preventingmachine.models.Transaction;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;

public class PageUserActivity extends Activity implements OnSMSMessageListener,
		OnSMSMessageFailListener
{
	private final static int TAB_SENSOR = 0;
	private final static int TAB_RELAY = TAB_SENSOR + 1;
	private final static int TOTAL_TABS = TAB_RELAY + 1;

	private SensorSQLite _SensorSQLite = null;
	private RelaySQLite _RelaySQLite = null;
	private ClientSQLite _ClientSQLite = null;

	private DeviceSQLite _DeviceSQLite = null;
	private AccountSQLite _AccountSQLite = null;

	private Account _Account = null;
	private Device _Device = null;

	private LinearLayout _LayoutListSensors = null;
	private LinearLayout _LayoutListRelays = null;

	private ScrollView _LayoutTabSensor = null;
	private ScrollView _LayoutTabRelay = null;

	private Client _Client = null;

	private Button _ButtonTabSensors = null;
	private Button _ButtonTabRelays = null;

	private Button _ButtonUpdateAllSensors = null;
	private Button _ButtonUpdateAllRelays = null;

	private ProgressBar _ProgressBarUpdateAllRelays = null;
	private ProgressBar _ProgressBarUpdateAllSensors = null;

	private List<Sensor> _SensorList = null;
	private List<Relay> _RelayList = null;

	private File _SoundAlarmDefault = null;
	private File _SoundAlarm = null;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		Utils.prepareWindow(this);

		setContentView(com.hethongviet.preventer.admin.R.layout.page_user);

		_LayoutListSensors = (LinearLayout) findViewById(com.hethongviet.preventer.admin.R.id.list_sensors);
		_LayoutListRelays = (LinearLayout) findViewById(com.hethongviet.preventer.admin.R.id.list_relays);

		_LayoutTabRelay = (ScrollView) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_relays);
		_LayoutTabSensor = (ScrollView) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_sensors);

		_ButtonTabRelays = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_tab_relays);
		_ButtonTabSensors = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_tab_sensors);

		_ButtonUpdateAllRelays = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_update_all_relays);
		_ButtonUpdateAllSensors = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_update_all_sensors);

		_ProgressBarUpdateAllRelays = (ProgressBar) findViewById(com.hethongviet.preventer.admin.R.id.progress_bar_update_all_relays);
		_ProgressBarUpdateAllSensors = (ProgressBar) findViewById(com.hethongviet.preventer.admin.R.id.progress_bar_update_all_sensors);

		initTab();

		initDB();

		if (Config.IS_DEBUG_NOT_WAIT_ADMIN)
		{
			_Client = new Client();
			_Client.setControlled(true);
			_Client.setDeviceNumber(Constants.DEVICE_NUMBER_DEFAULT);

			_ClientSQLite.insert(_Client);

			if (Config.IS_DEBUG)
			{
				_Device = new Device(Constants.DEVICE_NUMBER_DEFAULT,
						Constants.MAX_SENSORS, Constants.MAX_RELAYS);

				_Account = new Account(Constants.PASSWORD_DEFAULT);
			}
			else
			{
				_Device = new Device("", Constants.MAX_SENSORS,
						Constants.MAX_RELAYS);

				_Account = new Account("");
			}

			_DeviceSQLite.insert(_Device);
			_AccountSQLite.insert(_Account);

		}

		List<Client> clients = null;

		try
		{
			clients = _ClientSQLite.getAll();
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		if (clients == null || clients.size() == 0)
		{
			_RelayList = null;
			_SensorList = null;
			_ButtonTabRelays.setVisibility(View.GONE);

			_Client = new Client();

			if (Config.IS_DEBUG)
			{
				_Device = new Device(Constants.DEVICE_NUMBER_DEFAULT,
						Constants.MAX_SENSORS, Constants.MAX_RELAYS);

				_Account = new Account(Constants.PASSWORD_DEFAULT);
			}
			else
			{
				_Device = new Device("", Constants.MAX_SENSORS,
						Constants.MAX_RELAYS);

				_Account = new Account("");
			}

			_DeviceSQLite.insert(_Device);
			_AccountSQLite.insert(_Account);

			startActivity(new Intent(this, PageLoginActivity.class));
		}
		else
		{
			_Client = clients.get(0);

			SMSHelper.setDeviceNumber(_Client.getDeviceNumber());
			SMSHelper.setMessageId(0);

			try
			{
				_SensorList = _SensorSQLite.getAll();
			} catch (Exception e)
			{
				e.printStackTrace();
			}

			try
			{
				_RelayList = _RelaySQLite.getAll();
			} catch (Exception e)
			{
				e.printStackTrace();
			}

			showListSensors(Constants.MAX_SENSORS, _SensorList);

			_ButtonTabSensors.setVisibility(!_Client.isAlarmed() ? View.GONE : View.VISIBLE);
			_LayoutTabSensor.setVisibility(!_Client.isAlarmed() ? View.GONE : View.VISIBLE);

			showListRelays(Constants.MAX_RELAYS, _RelayList);

			_ButtonTabRelays.setVisibility(!_Client.isControlled() ? View.GONE : View.VISIBLE);
			_LayoutTabRelay.setVisibility(!_Client.isControlled() ? View.GONE : View.VISIBLE);
		}

		if (Config.IS_DEBUG)
		{
			if (_SensorList == null || _SensorList.size() == 0)
				_SensorList = initListSensors(Constants.MAX_SENSORS);
			if (_RelayList == null || _RelayList.size() == 0)
				_RelayList = initListRelays(Constants.MAX_RELAYS);
		}

		_ButtonUpdateAllSensors.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				if (SMSHelper.getDeviceNumber() == null
						|| SMSHelper.getDeviceNumber().equals(""))
				{
					showDialogWithCatch(R.string.message_wait_for_admin);
					return;
				}

				/* Send SMS update all */
				SMSHelper.updateElement(SMSHelper.CODE_UPDATE_SENSOR,
						R.string.message_fail_update_sensors);
				debugSendSMS(SMSHelper.DEBUG_SMS_UPDATE_SENSORS);

				/* Disable buttons */
				_ButtonUpdateAllSensors.setClickable(false);
				_ButtonUpdateAllSensors.setTextColor(Color.GRAY);

				/* Wait */
				_ProgressBarUpdateAllSensors.setVisibility(View.VISIBLE);
			}
		});

		_ButtonUpdateAllRelays.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				if (SMSHelper.getDeviceNumber() == null
						|| SMSHelper.getDeviceNumber().equals(""))
				{
					showDialogWithCatch(R.string.message_wait_for_admin);
					return;
				}

				/* Send SMS update all */
				SMSHelper.updateElement(SMSHelper.CODE_UPDATE_RELAY,
						R.string.message_fail_update_relays);
				debugSendSMS(SMSHelper.DEBUG_SMS_UPDATE_RELAYS);

				/* Disable buttons */
				_ButtonUpdateAllRelays.setClickable(false);
				_ButtonUpdateAllRelays.setTextColor(Color.GRAY);

				/* Wait */
				_ProgressBarUpdateAllRelays.setVisibility(View.VISIBLE);
			}
		});

		/* Create file alarm sound */
		InputStream inputStream = getResources().openRawResource(
				com.hethongviet.preventer.admin.R.raw.alarm_default);
		String fileName = "alarm.mp3";
		FileOutputStream fileOutputStream;
		try
		{
			fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);

			byte[] bs = new byte[1024];
			while (inputStream.read(bs) > 0)
			{
				fileOutputStream.write(bs);
			}

			_SoundAlarm = _SoundAlarmDefault = new File(
					getFilesDir().getAbsolutePath() + "/" + fileName);
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		if (!Utils.isStringNull(_Client.getAlarmPath()))
		{
			_SoundAlarm = new File(_Client.getAlarmPath());
		}

		// debugSendSMS(SMSHelper.DEBUG_SMS_SYNCHRONIZE_NUMBERS_ALARM);
		// debugSendSMS(SMSHelper.DEBUG_SMS_ALARM);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater menuInflater = getMenuInflater();

		menuInflater.inflate(R.menu.page_user, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == R.id.menu_change_sound)
		{
			Intent intent = new Intent(this, PageChangeSoundActivity.class);
			intent.putExtra(
					Constants.EXTRA_SOUND_PATH,
					_SoundAlarm == null ? "" : (_SoundAlarm.getAbsolutePath().equals(_SoundAlarmDefault.getAbsolutePath())) ? "" : _SoundAlarm.getAbsolutePath());
			startActivityForResult(intent, Constants.REQUEST_CHANGE_SOUND);
		}
		if (item.getItemId() == com.hethongviet.preventer.admin.R.id.menu_login_admin)
		{
			startActivity(new Intent(this, PageLoginActivity.class));
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode == RESULT_OK)
		{
			if (requestCode == Constants.REQUEST_CHANGE_SOUND)
			{
				String path = data.getStringExtra(Constants.EXTRA_SOUND_PATH);
				if (path.equals(""))
				{
					_SoundAlarm = _SoundAlarmDefault;
				}
				else
				{
					_SoundAlarm = new File(path);
				}

				_Client.setAlarmPath(path);
				_ClientSQLite.insert(_Client);
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		return new DialogMessageBack(this, true, id, false);
	}

	private void showDialogWithCatch(final int id)
	{
		runOnUiThread(new Runnable()
		{

			@Override
			public void run()
			{
				try
				{
					showDialog(id);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});

	}

	private void initDB()
	{
		_SensorSQLite = new SensorSQLite(this,
				AppMain.getInstance().getDBName());
		_SensorSQLite.open();
		_SensorSQLite.close();

		_ClientSQLite = new ClientSQLite(this,
				AppMain.getInstance().getDBName());
		_RelaySQLite = new RelaySQLite(this, AppMain.getInstance().getDBName());

		_AccountSQLite = new AccountSQLite(this,
				AppMain.getInstance().getDBName());
		_DeviceSQLite = new DeviceSQLite(this,
				AppMain.getInstance().getDBName());
	}

	@Override
	protected void onResume()
	{

		SmsReceiverDefault.setOnSMSMessageListener(this);
		SMSHelper.setActivity(this);
		SMSHelper.setMessageId(0);

		super.onResume();
	}

	private List<Sensor> initListSensors(int totalSensors)
	{
		List<Sensor> sensors = new ArrayList<Sensor>();

		for (int index = 0; index < totalSensors; index++)
		{
			Sensor sensor = new Sensor();
			sensor.setIndex(index);
			sensor.setName("Sensor " + (index + 1));

			sensors.add(sensor);
		}

		return sensors;
	}

	private List<Relay> initListRelays(int totalRelays)
	{
		List<Relay> relays = new ArrayList<Relay>();

		for (int index = 0; index < totalRelays; index++)
		{
			Relay relay = new Relay();
			relay.setIndex(index);
			relay.setName("Relay " + (index + 1));
			relay.setOn(true);

			relays.add(relay);
		}

		return relays;
	}

	private void initTab()
	{

		// TabHost tabHost = (TabHost) findViewById(R.id.tab);
		// tabHost.setup();
		//
		// TabSpec tabSpecSensor =
		// tabHost.newTabSpec(getString(R.string.sensors));
		// tabSpecSensor.setContent(R.id.tab_content_sensor);
		// tabSpecSensor.setIndicator(getString(R.string.sensors));
		//
		// TabSpec tabSpecRelay =
		// tabHost.newTabSpec(getString(R.string.relays));
		// tabSpecRelay.setContent(R.id.tab_content_relay);
		// tabSpecRelay.setIndicator(getString(R.string.relays));
		//
		// tabHost.addTab(tabSpecSensor);
		// tabHost.addTab(tabSpecRelay);

		/* Process for tab menu */
		Tab[] tabs = new Tab[TOTAL_TABS];

		tabs[TAB_SENSOR] = new Tab();
		tabs[TAB_SENSOR].setButton(_ButtonTabSensors);
		tabs[TAB_SENSOR].setViewContain(_LayoutTabSensor);

		tabs[TAB_RELAY] = new Tab();
		tabs[TAB_RELAY].setButton(_ButtonTabRelays);
		tabs[TAB_RELAY].setViewContain(_LayoutTabRelay);

		new TabMenu(tabs, R.drawable.button_tab2,
				R.drawable.button_tab2_highlight);

	}

	@Override
	public void onSMSMessageIncoming(SMS sms)
	{

		Utils.debug("Message receive = " + sms.getMessage());
		String message = Utils.prepareMessage(sms.getMessage());

		if (Utils.isStringNull(message))
		{
			Utils.debug("ERROR----- wrong message! NULL");
			return;
		}

		if (message.contains(SMSHelper.CODE_ALARM))
		{

			/* Notification and sound */
			final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

			String messageAlarm = getString(R.string.message_alarm);

			if (_SensorList != null && _SensorList.size() > 0)
			{
				String messageTemp = "";

				try
				{
					messageTemp = message.substring(
							SMSHelper.CODE_ALARM.length() + 1,
							message.length() - 2);

				} catch (Exception e)
				{
					e.printStackTrace();
					messageTemp = "";
				}

				int sensorIndex = -1;
				if (!messageTemp.equals(""))
				{
					try
					{
						sensorIndex = Integer.parseInt(messageTemp);
					} catch (Exception e)
					{
						e.printStackTrace();
						sensorIndex = -1;
					}
				}

				if (sensorIndex > 0 && sensorIndex < _SensorList.size())
				{
					messageTemp = _SensorList.get(sensorIndex).getName();
				}

				messageAlarm += " " + messageTemp;

			}

			final DialogAlarm dialogMessage = new DialogAlarm(this, true);
			dialogMessage.show(messageAlarm, false, notificationManager);

			final Notification notification = new Notification();
			// notification.flags |= Notification.FLAG_NO_CLEAR;
			notification.flags |= Notification.FLAG_INSISTENT;
			notification.icon = R.drawable.synchronize_error;
			notification.when = System.currentTimeMillis();
			notification.defaults |= Notification.DEFAULT_VIBRATE;

			Intent intent = new Intent(getApplication(), PageUserActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

			notification.contentIntent = PendingIntent.getActivity(
					getApplication(), 0, intent,
					PendingIntent.FLAG_UPDATE_CURRENT);

			RemoteViews contentView = new RemoteViews(
					getPackageName(),
					com.hethongviet.preventer.admin.R.layout.remote_view_notification);

			contentView.setImageViewResource(
					com.hethongviet.preventer.admin.R.id.image, R.drawable.logo);
			contentView.setTextViewText(
					com.hethongviet.preventer.admin.R.id.name,
					getText(R.string.app_name));
			contentView.setTextViewText(
					com.hethongviet.preventer.admin.R.id.state, messageAlarm);
			notification.contentView = contentView;

			notificationManager.notify(0, notification);

			SoundPlay.play(_SoundAlarm, -1);

		}
		else if (message.contains(SMSHelper.CODE_SYNCHRONIZE_NUMBERS_ALARM))
		{
			Utils.debug("CODE_SYNCHRONIZE_NUMBERS_ALARM");

			String messageContent = SMSHelper.getContent(message,
					SMSHelper.CODE_SYNCHRONIZE_NUMBERS_ALARM.length());

			if (Utils.isStringNull(messageContent))
			{
				Utils.debug("ERROR----- wrong messageContent! NULL");
				return;
			}

			String[] strings = messageContent.split("["
					+ SMSHelper.CODE_SEPARATE + "]");

			if (strings == null || strings.length < 2)
			{
				Utils.debug("ERROR----- wrong messageContent.split! NULL");
				return;
			}

			String number = strings[0];

			int totalSensors = Constants.MAX_SENSORS;

			try
			{
				totalSensors = Integer.parseInt(strings[1]);
			} catch (NumberFormatException e)
			{
				e.printStackTrace();
			}

			_Client.setAlarmed(true);
			_Client.setControlled(false);
			_Client.setDeviceNumber(number);

			_ClientSQLite.insert(_Client);
			SMSHelper.setDeviceNumber(number);

			runOnUiThread(new Runnable()
			{

				@Override
				public void run()
				{
					Toast.makeText(PageUserActivity.this,
							getString(R.string.message_receive_from_admin),
							Toast.LENGTH_LONG).show();

				}
			});

			_SensorSQLite.deleteAll();
			_SensorList = new ArrayList<Sensor>();
			for (int i = 0; i < totalSensors; i++)
			{
				Sensor sensor = new Sensor(strings[i + 1], i + 2);
				_SensorList.add(sensor);
				_SensorSQLite.insert(sensor);
			}

			_SensorList = _SensorSQLite.getAll();

			showListSensors(totalSensors, _SensorList);

			SMSHelper.synchronizeOfUser(sms.getRecipient(),
					SMSHelper.CODE_SYNCHRONIZE_NUMBERS_ALARM,
					message.substring(message.length() - 3, message.length()));

			if (_ButtonTabRelays.getVisibility() == View.VISIBLE)
			{
				_ButtonTabRelays.setVisibility(View.GONE);
				_LayoutTabRelay.setVisibility(View.GONE);
			}

			_ButtonTabSensors.setVisibility(View.VISIBLE);
			_LayoutTabSensor.setVisibility(View.VISIBLE);
		}
		else if (message.contains(SMSHelper.CODE_SYNCHRONIZE_NUMBERS_CONTROL))
		{

			Utils.debug("CODE_SYNCHRONIZE_NUMBERS_CONTROL");

			String messageContent = SMSHelper.getContent(message,
					SMSHelper.CODE_SYNCHRONIZE_NUMBERS_CONTROL.length());

			if (Utils.isStringNull(messageContent))
			{
				Utils.debug("ERROR----- wrong messageContent! NULL");
				return;
			}

			String[] strings = messageContent.split("["
					+ SMSHelper.CODE_SEPARATE + "]");

			if (strings == null || strings.length < 2)
			{
				Utils.debug("ERROR----- wrong messageContent.split! NULL");
				return;
			}

			String number = strings[0];

			int totalRelays = Constants.MAX_RELAYS;

			try
			{
				totalRelays = Integer.parseInt(strings[1]);
			} catch (NumberFormatException e)
			{
				e.printStackTrace();
			}

			runOnUiThread(new Runnable()
			{

				@Override
				public void run()
				{
					Toast.makeText(PageUserActivity.this,
							getString(R.string.message_receive_from_admin),
							Toast.LENGTH_LONG).show();

					_ButtonTabRelays.setVisibility(View.VISIBLE);
				}
			});

			_Client.setControlled(true);
			_Client.setAlarmed(false);
			_Client.setDeviceNumber(number);

			SMSHelper.setDeviceNumber(number);
			_ClientSQLite.insert(_Client);

			_RelaySQLite.deleteAll();
			_RelayList = new ArrayList<Relay>();
			for (int i = 0; i < totalRelays; i++)
			{
				Relay relay = new Relay(strings[i + 1], i + 2, false);
				_RelayList.add(relay);
				_RelaySQLite.insert(relay);
			}

			_RelayList = _RelaySQLite.getAll();

			showListRelays(totalRelays, _RelayList);

			SMSHelper.synchronizeOfUser(sms.getRecipient(),
					SMSHelper.CODE_SYNCHRONIZE_NUMBERS_CONTROL,
					message.substring(message.length() - 3, message.length()));

			if (_ButtonTabSensors.getVisibility() == View.VISIBLE)
			{
				_ButtonTabSensors.setVisibility(View.GONE);
				_LayoutTabSensor.setVisibility(View.GONE);
			}

			_ButtonTabRelays.setVisibility(View.VISIBLE);
			_LayoutTabRelay.setVisibility(View.VISIBLE);
		}
		else
		{
			Utils.debug("Message receive valid = " + message);
			Transaction transaction = SMSHelper.solve(message);

			if (transaction != null)
			{
				String codeSMS = transaction.getCodeSend();
				Utils.debug("codeSMS = " + codeSMS);

				if (codeSMS == null || codeSMS.equals(""))
				{
					Utils.debug("ERROR----- wrong message! NULL");
					return;
				}

				String contentSMS = transaction.getMessageReceive();
				Utils.debug("contentSMS = " + contentSMS);

				if (codeSMS.equals(SMSHelper.CODE_UPDATE_ALL))
				{
					/* User page not use */

					Utils.debug("CODE_UPDATE_ALL");
				}
				else if (codeSMS.equals(SMSHelper.CODE_UPDATE_RELAY))
				{
					Utils.debug("CODE_UPDATE_RELAY");
					final int INDEX_RELAY_NAMES = 0;
					final int INDEX_RELAY_STATUS = INDEX_RELAY_NAMES + 1;
					final int INDEX_DEVICE_NAME = INDEX_RELAY_STATUS + 1;
					@SuppressWarnings("unused")
					final int INDEX_DEVICE_TEMPERATURE = INDEX_DEVICE_NAME + 1;

					String insideMessage = contentSMS.substring(1,
							contentSMS.length() - 3);
					Utils.debug("insideMessage = " + insideMessage);

					String[] strings = insideMessage.split("[-]");

					/* Names */

					String relayNames = strings[INDEX_RELAY_NAMES].substring(1,
							strings[INDEX_RELAY_NAMES].length() - 1);
					String[] names = relayNames.split("[)(]+");
					Utils.debug("Names size = " + names.length);

					String status = strings[INDEX_RELAY_STATUS].substring(1,
							strings[INDEX_RELAY_STATUS].length() - 1);
					Utils.debug("status = " + status);

					for (int indexName = 0; indexName < names.length; indexName++)
					{
						_RelayList.get(indexName).setName(names[indexName]);

						char c = status.charAt(indexName);
						if (c == '0')
						{
							_RelayList.get(indexName).setOn(false);
						}
						else
						{
							_RelayList.get(indexName).setOn(true);
						}

						_RelaySQLite.insert(_RelayList.get(indexName));

						/* Update UI */
						View view = _LayoutListRelays.getChildAt(indexName);
						if (view != null)
						{
							Button button = (Button) view.findViewById(R.id.layout_one_relay_button);
							if (button != null)
							{
								button.setText(names[indexName]);

								button.setBackgroundDrawable(getResources().getDrawable(
										c == '0' ? R.drawable.button_off : R.drawable.button_on));
							}
						}
					}

					_ProgressBarUpdateAllRelays.setVisibility(View.GONE);
					_ButtonUpdateAllRelays.setClickable(true);
					_ButtonUpdateAllRelays.setTextColor(Color.BLACK);

					showListRelays(Constants.MAX_RELAYS, _RelayList);
				}
				else if (codeSMS.equals(SMSHelper.CODE_UPDATE_SENSOR))
				{
					Utils.debug("CODE_UPDATE_SENSOR");
					String insideMessage = contentSMS.substring(2,
							contentSMS.length() - 4);
					Utils.debug("insideMessage = " + insideMessage);

					String[] names = insideMessage.split("[)(]+");
					Utils.debug("Names size = " + names.length);

					for (int indexName = 0; indexName < names.length; indexName++)
					{
						/* Update db */
						_SensorList.get(indexName).setName(names[indexName]);
						_SensorSQLite.insert(_SensorList.get(indexName));

						/* Update UI */
						View view = _LayoutListSensors.getChildAt(indexName);
						if (view != null)
						{
							Button button = (Button) view.findViewById(R.id.layout_one_sensor_button);
							if (button != null)
								button.setText(names[indexName]);
						}
					}

					_ProgressBarUpdateAllSensors.setVisibility(View.GONE);
					_ButtonUpdateAllSensors.setClickable(true);
					_ButtonUpdateAllSensors.setTextColor(Color.BLACK);

					showListSensors(Constants.MAX_SENSORS, _SensorList);
				}
				else if (codeSMS.equals(SMSHelper.CODE_CONTROL_DEVICE))
				{
					Utils.debug("CODE_CONTROL_DEVICE contentSMS = "
							+ contentSMS);

					View viewRelay = transaction.getViewRelay();

					if (contentSMS.contains(SMSHelper.CODE_ERROR))
					{

						if (viewRelay != null)
						{
							ProgressBar progressBar = (ProgressBar) viewRelay.findViewById(R.id.layout_one_relay_progress_bar);

							progressBar.setVisibility(View.GONE);

							Button button = (Button) viewRelay.findViewById(R.id.layout_one_relay_button);
							button.setClickable(true);
							button.setTextColor(Color.BLACK);
						}

						showDialogWithCatch(R.string.message_error_control_relay);
						return;
					}

					/* message send: "(10b00000)" */
					String messageSent = transaction.getMessageSent();
					String insideMessage = messageSent.substring(1,
							messageSent.length() - 2);
					/* "10b00000" */

					_RelaySQLite.deleteAll();

					for (int indexStatus = 0; indexStatus < insideMessage.length(); indexStatus++)
					{

						char c = insideMessage.charAt(indexStatus);
						if (c == 'b')
						{
							_RelaySQLite.insert(_RelayList.get(indexStatus));
							continue;
						}

						boolean isOn = (c == '1');
						_RelayList.get(indexStatus).setOn(isOn);
						_RelaySQLite.insert(_RelayList.get(indexStatus));

						/* Update UI */
						if (viewRelay != null)
						{
							ProgressBar progressBar = (ProgressBar) viewRelay.findViewById(R.id.layout_one_relay_progress_bar);

							progressBar.setVisibility(View.GONE);

							Button button = (Button) viewRelay.findViewById(R.id.layout_one_relay_button);
							if (button != null)
							{
								button.setBackgroundDrawable(getResources().getDrawable(
										isOn ? R.drawable.button_on : R.drawable.button_off));

								button.setClickable(true);
								button.setTextColor(Color.BLACK);
							}

						}
						break;
					}

				}
			}
		}
	}

	private void showListSensors(int maxSensors, final List<Sensor> sensors)
	{
		int sensorLength = (sensors != null) ? sensors.size() : 0;
		int totalReal = (maxSensors > sensorLength) ? sensorLength : maxSensors;
		_LayoutListSensors.removeAllViews();
		if (totalReal != 0)
		{

			final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			for (int index = 0; index < totalReal; index++)
			{
				final View view = layoutInflater.inflate(
						R.layout.layout_one_sensor, null);

				final ViewHolderSensor holder = new ViewHolderSensor();
				holder.button = (Button) view.findViewById(R.id.layout_one_sensor_button);
				holder.textView = (TextView) view.findViewById(R.id.layout_one_sensor_index);

				final Sensor sensor = sensors.get(index);

				holder.button.setText(sensor.getName());
				holder.textView.setText((index + 1) + "");

				_LayoutListSensors.addView(view);
			}
		}

	}

	private void showListRelays(int maxRelays, final List<Relay> relays)
	{
		int sensorLength = (relays != null) ? relays.size() : 0;
		final int totalReal = (maxRelays > sensorLength) ? sensorLength : maxRelays;
		_LayoutListRelays.removeAllViews();
		if (totalReal != 0)
		{

			final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			for (int index = 0; index < totalReal; index++)
			{
				final View view = layoutInflater.inflate(
						R.layout.layout_one_relay, null);

				final ViewHolderRelay holder = new ViewHolderRelay();
				holder.progressBar = (ProgressBar) view.findViewById(R.id.layout_one_relay_progress_bar);
				holder.button = (Button) view.findViewById(R.id.layout_one_relay_button);
				holder.textView = (TextView) view.findViewById(R.id.layout_one_relay_index);

				final Relay relay = relays.get(index);

				holder.textView.setText((index + 1) + "");
				holder.button.setText(relay.getName());
				holder.button.setBackgroundDrawable(getResources().getDrawable(
						relay.isOn() ? R.drawable.button_on : R.drawable.button_off));
				holder.progressBar.setVisibility(View.GONE);

				final int indexRelay = index;

				holder.button.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{
						/* SMS turn relay */
						SMSHelper.controlRelay(totalReal, indexRelay,
								!relay.isOn(),
								R.string.message_fail_control_relay, view);
						debugSendSMS(SMSHelper.DEBUG_SMS_CONTROL_DEVICE);

						/* Wait */
						holder.progressBar.setVisibility(View.VISIBLE);
						holder.button.setClickable(false);
					}
				});

				_LayoutListRelays.addView(view);
			}

		}

	}

	private static class ViewHolderSensor
	{
		Button button = null;
		TextView textView = null;
	}

	private static class ViewHolderRelay
	{
		ProgressBar progressBar = null;
		Button button = null;
		TextView textView = null;
	}

	private void debugSendSMS(final String message)
	{

		final SMS sms = new SMS();
		sms.setRecipient(SMSHelper.getDeviceNumber());
		sms.setMessage(message);

		if (Config.IS_DEBUG_SMS_RECEIVE)
		{
			new Thread(new Runnable()
			{

				@Override
				public void run()
				{
					try
					{
						Thread.sleep(Constants.TIME_DEBUG_SEND_SMS);
					} catch (Exception e)
					{
						e.printStackTrace();
					}
					PageUserActivity.this.runOnUiThread(new Runnable()
					{

						@Override
						public void run()
						{
							onSMSMessageIncoming(sms);
						}
					});
				}
			}).start();

		}
	}

	@Override
	public void onSMSMessageFail(final Transaction transaction,
			final int messageFailId)
	{
		runOnUiThread(new Runnable()
		{

			@Override
			public void run()
			{
				if (messageFailId > 0)
					Toast.makeText(PageUserActivity.this,
							getString(messageFailId), Toast.LENGTH_LONG).show();

				switch (messageFailId)
				{
				case R.string.message_fail_control_relay:

					View viewRelay = transaction.getViewRelay();
					if (viewRelay == null)
						break;

					ProgressBar progressBar = (ProgressBar) viewRelay.findViewById(R.id.layout_one_relay_progress_bar);
					progressBar.setVisibility(View.GONE);

					Button button = (Button) viewRelay.findViewById(R.id.layout_one_relay_button);
					button.setClickable(true);
					button.setTextColor(Color.BLACK);

					break;

				case R.string.message_fail_update_relays:

					_ProgressBarUpdateAllRelays.setVisibility(View.GONE);
					_ButtonUpdateAllRelays.setClickable(true);
					_ButtonUpdateAllRelays.setTextColor(Color.BLACK);

					break;

				case R.string.message_fail_update_sensors:

					_ProgressBarUpdateAllSensors.setVisibility(View.GONE);
					_ButtonUpdateAllSensors.setClickable(true);
					_ButtonUpdateAllSensors.setTextColor(Color.BLACK);

					break;

				default:
					break;
				}
			}
		});

	}
}
